package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void saveAddressBook(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询地址列表
     * @return
     */
    @Override
    public List<AddressBook> listUserAddressBooks() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        return addressBookMapper.listAddressBook(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public List<AddressBook> getDefaultUserAddressBook() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);

        return addressBookMapper.listAddressBook(addressBook);
    }

    /**
     * 根据Id修改地址
     * @param addressBook
     */
    @Override
    public void updateAddressBookById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefaultUserAddressBook(AddressBook addressBook) {
        // 1. 先将当前用户的所有地址设置为非默认
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        // 2. 再将当前地址设置为默认
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据Id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        return addressBookMapper.selectById(id);
    }

    /**
     * 根据Id删除地址
     * @param id
     */
    @Override
    public void deleteAddressBookById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
